package cn.neusoft.controller;

import cn.neusoft.po.Product;
import cn.neusoft.query.ProductQuery;
import cn.neusoft.service.IProductService;
import cn.neusoft.vo.ResponseObj;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

/**
 * @author hxj
 * @since 2023-12-22
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService service;

    @PostMapping("/batch")
    public ResponseObj saveBatch(@RequestBody List<Product> productList){
        productList.forEach(product -> {
            product.setState(0L);
            product.setOnsaletime(new Date());
            product.setCreatetime(new Date());
        });
        boolean b = service.saveBatch(productList);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(80003,"批量添加成功");
    }

    @PostMapping
    public ResponseObj saveOrUpdate(@RequestBody Product product){
        if (product.getId()==null){
            product.setState(0L);
            product.setOnsaletime(new Date());
            product.setCreatetime(new Date());
        }
        boolean b = service.saveOrUpdate(product);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(80001,"保存商品信息失败");
    }

    @DeleteMapping("/{id}")
    public ResponseObj delete(@PathVariable("id") Integer id){
        boolean b = service.removeById(id);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(80002,"删除商品信息失败");
    }

    @GetMapping("/{id}")
    public ResponseObj getById(@PathVariable("id") Integer id){
        Product product = service.getById(id);
        return ResponseObj.SUCCESS(product);
    }

    @PostMapping("/page")
    public ResponseObj getByPage(@RequestBody ProductQuery query){
        //构建条件搜索对象
        Page<Product> page = service.getByPage(query);
        return ResponseObj.SUCCESS(page);
    }

    @GetMapping("/all")
    public ResponseObj getAll(){
        List<Product> list = service.list();
        return ResponseObj.SUCCESS(list);
    }
    
}
